package com.lxxie;

import org.mozilla.universalchardet.UniversalDetector;

import java.io.UnsupportedEncodingException;

/**
 * @Description TODO
 * @Date 2021/10/26 14:37
 * @Created by xielx
 */
public class EncodeTest {

    public static void main(String[] args) throws UnsupportedEncodingException {
        String str = "afdafdafe寺";
        byte[] bs1 = str.getBytes("gbk");
        byte[] bs2 = str.getBytes("utf-8");
        System.out.println(getEncoding(new byte[1]));
        System.out.println(getEncoding(bs2));
    }

    public static String getEncoding(byte[] bytes) {
        String defaultEncoding = "UTF-8";
        UniversalDetector detector = new UniversalDetector(null);
        detector.handleData(bytes, 0, bytes.length);
        detector.dataEnd();
        String encoding = detector.getDetectedCharset();
        detector.reset();
        if (encoding == null) {
            encoding = defaultEncoding;
        }
        return encoding;
    }
}
